<?php
/**
 * 原点 2020年5月29日17:12:08 支付宝微信支付类
 */

namespace app\common\controller;
use app\common\model\Account;
use app\common\model\Logs;
use app\index\model\Order;
use app\index\model\Group;

use app\index\model\Split;
use app\index\model\User;
use app\index\model\Goods;
use Pay\Pay;
use Pay\Alipay;
use Pay\Wxpay;
use think\Controller;
use Pay\Exceptions\InvalidArgumentException;
use think\Db;

class Payment extends Controller
{
    /**
     * @var array 支付配置参数
     */
    private $config;

    /**
     * @var string 商户订单号
     */
    private $out_trade_no;

    /**
     * @var float 支付金额
     */
    private $total_fee;

    /**
     * @var string 支付说明或者商品名称
     */
    private $body;

    /**
     * @var string 支付驱动 alipay | wechat
     */
    private $driver;

    /**
     * @var string  异步回调地址
     */
    private $notify_url;

    /**
     * @var string 同步跳转地址
     */
    private $return_url;

    /**
     * @var string 支付方式
     * （支付宝：web => 电脑支付; wap => 手机网站支付; app => APP支付）
     * （微信：mp => 公众号支付; miniapp => 小程序支付; wap => H5支付; scan => 扫码支付; app => App支付）
     */
    private $gateway;

    public function __construct(array $param = [])
    {
        $this->out_trade_no = $param['out_trade_no'];
        $this->total_fee = $param['total_fee'];
        $this->body = $param['body'];
        $this->notify_url = $param['notify_url'];
        $this->return_url = $param['return_url'];
        $this->gateway = $param['gateway'];
        $this->config = require '../extend/pay/config.php';
        include '../extend/pay/init.php';


    }

    public function driver($driver)
    {

        if (is_null($driver)) {
            throw new InvalidArgumentException('暂不支持此支付方式');
        }
        $this->driver = $driver;
        return $this;
    }


    public function payment()
    {


        if ($this->driver == 'wechat') {
            return $this->Wechat();
        }

        if ($this->driver == 'alipay') {
            return $this->Alipay();
        }
        return false;
    }


    protected function Wechat()
    {
        $options = [
            'out_trade_no' => $this->out_trade_no,
            'total_fee' => $this->total_fee * 100,
            'body' => $this->body,
            'spbill_create_ip' => request()->ip(),
            'notify_url' => $this->notify_url,
            'openid'=>session('openId')
        ];
        
        $return_url = $this->return_url;
        if ($this->gateway != 'app') {
            $pay = new Pay($this->config);
            $result = $pay->driver($this->driver)->gateway($this->gateway)->apply($options, $return_url);

        } else {
            //APP支付
            $wxPay = new Wxpay($this->config['wechat']);
            $result = $wxPay->WxPay($options);
        }

        return $result;

    }

    protected function Alipay()
    {
        $options = [
            'out_trade_no' => $this->out_trade_no,
            'total_fee' => $this->total_fee,
            'subject' => $this->body
        ];
        if ($this->gateway != 'app') {
            $this->config['alipay']['notify_url'] = $this->notify_url;
            $this->config['alipay']['return_url'] = $this->return_url;

            $pay = new Pay($this->config);

            $result = $pay->driver($this->driver)->gateway($this->gateway)->apply($options);
        } else {
            //APP支付
            $aliPay = new Alipay($this->config['alipay']);
            $result = $aliPay->AliPay($options);
        }
        return $result;
    }



    public function alipay_notify()
    {
        $pay = new Pay($this->config);
        $pay->driver('alipay')->gateway('wap')->verify($_POST);
        if ($_POST) {
            try {
                //根据订单号查询订单
                $order_model = new Order();
                $info = $order_model::get(['sn' => $_POST['out_trade_no']]);
                $time = time();
                if ($info && $info['state'] == 1) {
                    //更改订单状态
                    $user_model = new User();
                    $user = $user_model::get($info['uid']);
                    $order_model->Award($info['id'], $user['id']);
                    $order_model->save(['pay_state' => 2, 'pay_time' => $time, 'state' => 2], ['id' => $info['id']]);
                    $order_model->clear_redis($user['code']);
                    //如果是批购商品
                    $msg = '购买商品，订单ID【' . $info['id'] . '】';
                    if ($info['order_type'] == 1) {
                        $user_model->save(['is_active' => 2, 'pg_time' => $time], ['id' => $user['id']]);
                        $product_id = db('order_product')->where('order_id', $info['id'])->value('product_id');
                        $goods = Goods::get($product_id);
                        (new Split())->split($goods, $info['id'], $info['sn'], $time, $user);
                        $msg = '购买批购商品，订单ID【' . $info['id'] . '】,已拆分';
                    }
                    if (in_array($info['pay_way'], ['alipay_integral', 'wxpay_integral'])) {
                        //如果是组合支付需要扣除积分
                        Account::create_Inc($user['id'], $info['integral_amount'], 'integral', '购买商品', $info['id'], '-');
                    }

                    Logs::add($user['id'], $user['nickname'], $msg);
                    file_put_contents('notify/notify.txt', "支付成功订单编号:\r\n" . $info['sn'], FILE_APPEND);
                }
                return 'success';
            } catch (\Exception $e) {
                file_put_contents('notify/notify.txt', "抛异常:\r\n" . $e->getMessage(), FILE_APPEND);
                return 'success';
            }

        } else {
            file_put_contents('notify/notify.txt', "支付失败订单编号:\r\n" . $_POST['out_trade_no'], FILE_APPEND);
            return 'success';
        }
    }

    public function alipay_vip(){
        $pay = new Pay($this->config);
        $pay->driver('alipay')->gateway('wap')->verify($_POST);
        if ($_POST) {
            try {
                //根据订单号查询订单
                $info = db('member_vip_log')->where(['sn'=>$_POST['out_trade_no']])->find();

                if ($info && $info['state'] == 1) {
                    //更改订单状态
                    $user_model = new User();
                    $user = $user_model::get($info['uid']);
                    $param['is_active'] = 1;
                    $param['active_time'] = time();
                    $param['id_card'] = $info['id_card'];
                    $user_model->save($param, ['id' => $user['id']]);
                    Logs::add($user['id'], $user['nickname'], '申请成为VIP');
                    file_put_contents('notify/notify.txt', "支付成功订单编号:\r\n" . $info['sn'], FILE_APPEND);
                }
                return 'success';
            } catch (\Exception $e) {
                file_put_contents('notify/notify.txt', "抛异常:\r\n" . $e->getMessage(), FILE_APPEND);
                return 'success';
            }

        } else {
            file_put_contents('notify/notify.txt', "支付失败订单编号:\r\n" . $_POST['out_trade_no'], FILE_APPEND);
            return 'success';
        }
    }

    public function wechat_notify(){
        $pay = new Pay($this->config);
        $verify = $pay->driver('wechat')->gateway('wap')->verify(file_get_contents('php://input'));
        if ($verify) {
            try {
                //根据订单号查询订单
                $order_model = new Group();
                $info = $order_model::get(['sn' => $verify['out_trade_no']]);
                file_put_contents('notify/notify.txt', "支付成功订单编号:\r\n" . $info['sn'], FILE_APPEND);
                $goods=db('goods')->find($info['product_id']);
                $time = time();
                if ($info && $info['pay_state'] == 1) {
                    $user = Db::name('user')->where(['id'=>$info['uid']])->find();
                    $res = $order_model->join_group($info['id'],$user,'wechat',$goods);
                    if($res['code'] == -1){
                        file_put_contents('notify/notify.txt', "抛异常:\r\n" . json_encode($res), FILE_APPEND);
                    }else{
                        if($res['user']['is_auto']==1 && $res['is_open']==1){
                            //自动复购
                            $order_model->auto_buy($res['user'],$res['order'],$res['goods']);
                        }
                        file_put_contents('notify/notify.txt', "支付成功订单编号:\r\n" . $info['sn'], FILE_APPEND);
                    }
                }
                echo 'success';
            } catch (\Exception $e) {
                file_put_contents('notify/notify.txt', "抛异常:\r\n" . $e->getMessage(), FILE_APPEND);
                echo 'success';
            }
        } else {
            file_put_contents('notify/notify.txt', "收到异步通知\r\n", FILE_APPEND);
            echo "success";
        }

    }


    public function wechat_vip(){
        $pay = new Pay($this->config);
        $verify = $pay->driver('wechat')->gateway('wap')->verify(file_get_contents('php://input'));
        if ($verify) {
            try {
                //根据订单号查询订单
                $info = db('member_vip_log')->where(['sn'=>$verify['out_trade_no']])->find();

                if ($info && $info['state'] == 1) {
                    //更改订单状态
                    $user_model = new User();
                    $user = $user_model::get($info['uid']);
                    $param['is_active'] = 1;
                    $param['active_time'] = time();
                    $param['id_card'] = $info['id_card'];
                    $user_model->save($param, ['id' => $user['id']]);
                    Logs::add($user['id'], $user['nickname'], '申请成为VIP');
                    file_put_contents('notify/notify.txt', "支付成功订单编号:\r\n" . $info['sn'], FILE_APPEND);
                }
                echo 'success';
            } catch (\Exception $e) {
                file_put_contents('notify/notify.txt', "抛异常:\r\n" . $e->getMessage(), FILE_APPEND);
                echo 'success';
            }
        } else {
            file_put_contents('notify/notify.txt', "收到异步通知\r\n", FILE_APPEND);
            echo "success";
        }

    }

}